<template>
    <template v-for="(tag,index) in value" :key="tag">
        <a-input
                v-if="tagVisible == tag"
                :ref="(el)=>setRef(index,el)"
                type="text"
                size="small"
                :style="{ width: '78px' , marginRight:'7px'}"
                v-model:value="inputValue"
                @blur="tagInputConfirm(index)"
                @keyup.enter="tagInputConfirm(index)"
        />
        <a-tag v-else :closable="del" @close="handleClose(tag)" @click="tagEdit(index,tag)">{{tag}}</a-tag>
    </template>
    <template v-if="add">
        <a-input
                v-if="inputVisible"
                ref="inputRef"
                type="text"
                size="small"
                :style="{ width: '78px' }"
                v-model:value="inputValue"
                @blur="handleInputConfirm"
                @keyup.enter="handleInputConfirm"
        />
        <a-tag v-else style="background: #fff; border-style: dashed" @click="showInput" >
            <plus-outlined />
            {{ trans('FormMany.add') }}
        </a-tag>
    </template>
</template>

<script>
    export default {
        name: "ExDynamicTag",
    }
</script>
<script setup>
    import {trans} from "@/utils/index"
    import { pull } from 'lodash'
    import { useVModel } from '@vueuse/core'
    import {ref,nextTick,watch,computed} from "vue";
    const props = defineProps({
      value:Array,
      add: {
        type:Boolean,
        default:true
      },
      edit:{
        type:Boolean,
        default:true
      },
      del:{
        type:Boolean,
        default:true
      },
    })
    const emit = defineEmits(['update:value','change'])
    const value = useVModel(props, 'value',emit)
    const inputVisible = ref(false)
    const tagVisible = ref('')
    const inputRef = ref()
    const tagInputRef = ref([])
    const inputValue = ref('')
    function showInput(){
        inputValue.value  = ''
        inputVisible.value = true;
        nextTick(() => {
            inputRef.value.focus();
        });
    }
    watch(value,val=>{
      emit('change',val)
    },{deep:true})
    function tagInputConfirm(index){

        if(inputValue.value){
            value.value[index] = inputValue.value
        }
        tagVisible.value  = ''
        inputValue.value  = ''
    }
    function setRef(index,el) {
        tagInputRef.value[index] = el
    }
    function tagEdit(index,tag) {
        if(!props.edit){
          return false
        }
        inputValue.value = tag
        tagVisible.value = tag
        nextTick(() => {
            tagInputRef.value[index].focus();
        });
    }
    function handleClose(label) {
        pull(value.value,label)
    }
    function handleInputConfirm(){
        if(inputValue.value){
            value.value.push(inputValue.value)
        }
        inputVisible.value  = false
        inputValue.value  = ''
    }
</script>
<style scoped>

</style>